package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeignService productFeignService;
    @Autowired
    ThreadPoolExecutor executor;

    private static final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations ops = getBoundHashOperations();
        String res = (String) ops.get(skuId.toString());

        if (StringUtils.isBlank(res)) {
            CartItem item = new CartItem();

            CompletableFuture<Void> infoFuture = CompletableFuture.runAsync(() -> {
                R r = productFeignService.info(skuId);
                if (r.getCode() == 0) {
                    SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                    });

                    item.setCheck(true);
                    item.setCount(num);
                    item.setImage(skuInfo.getSkuDefaultImg());
                    item.setTitle(skuInfo.getSkuTitle());
                    item.setSkuId(skuId);
                    item.setPrice(skuInfo.getPrice());
                }
            }, executor);

            CompletableFuture<Void> valuesFuture = CompletableFuture.runAsync(() -> {
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                item.setSkuAttr(values);
            }, executor);

            try {
                CompletableFuture.allOf(infoFuture, valuesFuture).get();
            } catch (InterruptedException e) {
                log.error("获取item异常:{}", e);
            } catch (ExecutionException e) {
                log.error("获取item异常:{}", e);
            }

            String s = JSON.toJSONString(item);
            ops.put(skuId.toString(), s);
            return item;
        } else {
            CartItem item = JSON.parseObject(res, CartItem.class);
            item.setCount(item.getCount() + num);
            ops.put(skuId.toString(), JSON.toJSONString(item));

            return item;
        }

    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations ops = getBoundHashOperations();
        String s = (String) ops.get(skuId.toString());

        return JSON.parseObject(s, CartItem.class);
    }

    @Override
    public Cart getCart() {
        Cart cart = new Cart();
        UserInfoTo userInfo = CartInterceptor.threadLocal.get();
        String tempCartKey = CART_PREFIX + userInfo.getUserKey();
        if (userInfo.getUserId() != null) {
            String cartKey = CART_PREFIX + userInfo.getUserId();
            List<CartItem> list = getCartItems(tempCartKey);
            if (list != null) {
                for (CartItem item : list) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                clearCart(tempCartKey);
            }
            List<CartItem> items = getCartItems(cartKey);
            cart.setItems(items);
        } else {
            String cartKey = tempCartKey;
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }

        return cart;
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations ops = getBoundHashOperations();
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        String s = JSON.toJSONString(cartItem);
        ops.put(skuId.toString(), s);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations ops = getBoundHashOperations();
        ops.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        getBoundHashOperations().delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfo = CartInterceptor.threadLocal.get();
        if (userInfo.getUserId() == null) {
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfo.getUserId();
            List<CartItem> cartItems = getCartItems(cartKey);
            List<CartItem> collect = cartItems.stream().filter(item -> item.getCheck())
                    .map(item -> {
                        BigDecimal price = productFeignService.getPrice(item.getSkuId());
                        item.setPrice(price);
                        return item;
                    }).collect(Collectors.toList());
            return collect;
        }

    }

    private void clearCart(String tempCartKey) {
        redisTemplate.delete(tempCartKey);
    }

    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (!CollectionUtils.isEmpty(values)) {
            List<CartItem> collect = values.stream().map(item -> {
                String s = (String) item;
                CartItem cartItem = JSON.parseObject(s, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return collect;
        }

        return null;
    }

    private BoundHashOperations getBoundHashOperations() {
        UserInfoTo userInfo = CartInterceptor.threadLocal.get();
        String cartKey;
        if (userInfo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfo.getUserKey();
        }
        return redisTemplate.boundHashOps(cartKey);
    }
}
